//
//  REMClientDelegateObservable.swift
//  rxemclient
//
//  Created by yangjian on 2023/4/14.
//

import UIKit
import HyphenateChat
import RxSwift


enum IMClientLogoutReason {
    case none //启动APP时默认状态
    case disconnected
    case autoLoginError(_ error : EMError)
    case userAccountDidLoginFromOtherDevice
    case userAccountDidRemoveFromServer
    case userDidForbidByServer
    case userAccountDidForced(_ error : EMError)
}

enum IMClientLoginState {
    case login
    case logout(_ reason : IMClientLogoutReason)
}

class RXEMClientObservable: NSObject ,EMClientDelegate{
    
    public let rx_loginState = BehaviorSubject<IMClientLoginState>(
        value: EMClient.shared().isAutoLogin ? .login : .logout(.none));
    
    public let rx_connectionStateDidChange = PublishSubject<EMConnectionState>();
//    public let rx_autoLoginDidCompleteWithError = PublishSubject<EMError?>();
//    public let rx_userAccountDidLoginFromOtherDevice = PublishSubject<Void>();
//    public let rx_userAccountDidRemoveFromServer = PublishSubject<Void>();
//    public let rx_userDidForbidByServer = PublishSubject<Void>();
//    public let rx_userAccountDidForced = PublishSubject<EMError>();
    public let rx_tokenWillExpire = PublishSubject<EMErrorCode>();
    public let rx_tokenDidExpire = PublishSubject<EMErrorCode>();

    
    
    func connectionStateDidChange(_ aConnectionState: EMConnectionState) {
        rx_connectionStateDidChange.onNext(aConnectionState);
    }
    func autoLoginDidCompleteWithError(_ aError: EMError?) {
        guard let aError = aError else { return }
        rx_loginState.onNext(.logout(.autoLoginError(aError)))
//        rx_autoLoginDidCompleteWithError.onNext(aError);
    }
    func userAccountDidLoginFromOtherDevice() {
        rx_loginState.onNext(.logout(.userAccountDidLoginFromOtherDevice))
    }
    func userAccountDidRemoveFromServer() {
        rx_loginState.onNext(.logout(.userAccountDidRemoveFromServer))
    }
    func userDidForbidByServer() {
        rx_loginState.onNext(.logout(.userDidForbidByServer))
    }
    func userAccountDidForced(toLogout aError: EMError?) {
        guard let aError = aError else{ return }
        rx_loginState.onNext(.logout(.userAccountDidForced(aError)))
    }
    func tokenWillExpire(_ aErrorCode: EMErrorCode) {
        rx_tokenWillExpire.onNext(aErrorCode);
    }
    func tokenDidExpire(_ aErrorCode: EMErrorCode) {
        rx_tokenDidExpire.onNext(aErrorCode);
    }
}
